<template>
  <div v-loading="loading">
    <MyAlert
      type="success"
      style="margin-bottom: -5px; margin-left: 55px; width: 700px"
      message="为了保证敏感信息的安全性，只能保存不能查看，如果没有输入则会使用上一次输入的值"
    />
    <DiyFormRender
      class="ml-3"
      :form-id="connectTmpl?.diyFormId"
      diy-field-name="fields"
      :beforeFormSchema="getBeforeFormSchema"
      :afterFormSchema="getAfterFormSchema"
      ref="diyFormRenderRef"
    >
      <template #connect-app="{ model, field }">
        <a-form-item-rest>
          <div class="flex flex-wrap" v-if="idpConnect.id">
            <a-card hoverable 
              :bordered="false" style="width: 270px;  background: #fafbfc;" class="mb-3 mr-3"  
              v-for="item in connectAppList[0].appList" :key="item.appId"
            >
              <div class="app-card">
                <div class="app-logo">
                  <img :src="item.logo || defaultLogo" />
                </div>
                <div class="app-name">
                  {{ item.name }}
                </div>

                <div class="switch">
                  <Switch class="extra" checked-children="开" un-checked-children="关" @change="(enabled) => handleChangeApp(item, enabled)" v-model:checked="item.enabled"/>
                </div>
              </div>
            </a-card>
          </div>
        </a-form-item-rest>
    
      </template>
      <template #footer-action="{ model, field }">
        <a-button class="mr-5">重置</a-button>
        <a-button type="primary" @click="handleSubmit">保存</a-button>

        <a-alert
          v-if="idpConnect?.id" style="margin-top: 20px;" message="删除身份源连接："
          show-icon
          description="删除后开启该身份源连接的应用将失去该连接方式"
          type="warning"
        >
          <template #action>
            <a-button type="primary" danger @click="handleDelete">删除</a-button>
          </template>
        </a-alert>
      </template>
    </DiyFormRender>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, watch, onMounted, nextTick } from "vue"
  import { Radio, Switch } from "ant-design-vue";
  import MyAlert from "/@/components/My/MyAlert.vue"
  import defaultLogo from "/@/assets/images/default-app.png"
  import DiyFormRender from "/@/views/diyDesigner/render-page/DiyFormRender.vue"
  import { beforeFormSchema, afterFormSchema } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import * as extIdpApi from "/@/api/iam/extIdp"
  import { isString } from "/@/utils";

  const { createMessage } = useMessage()
  const diyFormRenderRef = ref<InstanceType<typeof DiyFormRender>>()
  const idpConnect = ref()
  const props = defineProps({
    index: { type: Number, required: true },
    connectTmpl: { type: Object, required: true },
    idpId: { type: String, required: true },
    idpConnect: { type: Object, required: false },
  })

  const emit = defineEmits(["save", "delete", "register"])

  const loading = ref(false)
  const connectAppList = ref<any[]>([])
  const getBeforeFormSchema = computed(() => beforeFormSchema)
  const getAfterFormSchema = computed(() => {
    const schemas = [ ...afterFormSchema ]
    schemas.push({
      label: "关联应用",
      itemProps: {
        colon: false
      },
      helpMessage: [
        '一个应用只能绑定一个身份源',
        '如果某个身份源已经绑定其他身份源会先取消原有的再绑定新的'
      ],
      ifShow: ({ }) => connectAppList.value.length > 0,
      colProps: { span: 24 },
      field: "connect-app",
      component: "Input",
      slot: 'connect-app'
    })
    schemas.push({
      label: ' ',
      itemProps: {
        colon: false
      },
      colProps: { span: 12 },
      field: "footer-action",
      component: "Input",
      slot: 'footer-action'
    })
    return schemas
  })


  onMounted(() => {

  })

  watch(
    () => props.connectTmpl,
    (val: any) => {
      if (!val) {
        return
      }
      console.log('connectTmpl', props.connectTmpl)

      nextTick(() => {
        diyFormRenderRef.value?.setValues({ idpConnectType: props.connectTmpl.type})
      })
    }, { immediate: true, deep: true }
  )


  watch(
    () => props.idpConnect,
    (val: any) => {
      if (!val) {
        return
      }
      console.log('form-value', val)
      if (idpConnect.value?.id != val.id) {
        extIdpApi.listIdpConnectApp({ idpConnectId: val.id}).then(data => {
          connectAppList.value = data
        })
      }
      idpConnect.value = val

      nextTick(() => {
        let accountBind = true
        if (val.associationWay == 'none') {
          accountBind = false
        }
        diyFormRenderRef.value?.setValues({ ...idpConnect.value, accountBind })
      })

    }, { immediate: true, deep: true }
  )

  const handleChangeApp = async (app, enabled) => {
    console.log('handleChangeApp', app)
    loading.value = true
    try {
      await handleSubmit(false)
      await extIdpApi.updateIdpConnectApp({ 
        idpConnectId: idpConnect.value.id, 
        appId: app.appId, enabled: enabled 
      })
      createMessage.success(enabled ? "关联身份源成功" : "取消关联身份源成功")
    } catch(e) {
      console.error(e)
      app.enabled = !enabled
    } finally {
      loading.value = false
    } 
  }

  async function handleDelete() {
    loading.value = true
    try {
      await extIdpApi.deleteIdpConnect({ id: idpConnect.value.id })
      emit("delete", props.index)
    } finally {
      loading.value = false
    }
  }

  async function handleSubmit(showLoading = true) {
    loading.value = !showLoading ? loading.value : true
    try {
      const isUpdate = !!idpConnect.value?.id
      let values = await diyFormRenderRef.value?.getValues()
      // const formValues = diyFormField.getSubmitFormValue(values)
      delete values["footer-action"]
      const formValues = {
        ...values,
        idpId: props.idpId,
        connectTmplId: props.connectTmpl.id,
        type: props.connectTmpl.type,
        loginOnly: true
        // authClientIds: unref(checkedClient)?.split(","),
      }

      if (formValues.fields.scopes && isString(formValues.fields.scopes)) {
        formValues.fields.scopes = formValues.fields.scopes.split(',')
      }

      formValues.bindMethods = isString(formValues.bindMethods) ? formValues.bindMethods?.split(',') : formValues.bindMethods
      formValues.matchFields = isString(formValues.matchFields) ? formValues.matchFields?.split(',') : formValues.matchFields

      if (!values.accountBind) {
        formValues.associationWay = 'none'
      }
      delete formValues.accountBind

      console.log("formValues", formValues)
      const id = await extIdpApi.saveIdpConnect(formValues, isUpdate)
      emit("save", props.index, { ...formValues, id })
      showLoading && createMessage.success("保存成功")
    } finally {
      loading.value = !showLoading ? loading.value : false
    }
  }
</script>

<style lang="less">

.ant-form-item {
  margin-right: 10px !important;
}

.app-card {
  display: flex;
  align-items: center;
  align-content: center;
  border-radius: 10px;
  margin-right: 14px;
  margin-bottom: 14px;
  margin: 0 auto; 

  .app-logo {
    width: 64px;
    // height: 45px;
    padding-left: 24px;
  }

  .app-name {
    flex: 1 1;
    max-width: 138px;
    padding-left: 8px;
    white-space: normal;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}

</style>
